<?php

namespace app\admin\service;

use app\admin\model\Villages;
use app\admin\model\Member;
use app\admin\model\Image;

use think\Db;
use think\Exception;

class Dynamic
{

    /**
     * 格式化动态列表
     */
    public static function formatDynamicList($list, $userId, $userInfo = ''){
        foreach ($list as &$item) {
            $item = self::formatDynamic($item, $userId, $userInfo);
        }

        return $list;
    }

    /**
     * 格式化动态
     */
    public static function formatDynamic($item, $userId, $userInfo = ''){
        if(!$item){
            return '';
        }

        $userDB = db('user');
        //$dynamicscommentDB = db('dynamicscomment');
        $dynamicslikeDB = db('articlelike');
        $userattentionDB = db('userattention');

        if(!$userInfo){
            $userInfo = $userDB->where(['id' => $item['userId']])->field('id,memberId,nickName,avatarUrl')->find();
        }
        $item['userId'] = $userInfo['id'];
        $item['userName'] = $userInfo['nickName'];
        $item['userAvatar'] = $userInfo['avatarUrl'];
        // 处理动态内容
        $item['content'] = urldecode($item['content']);
        // 动态图集
        $imagesList = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->field('imgUrl')->order('sorting ASC')->select();
        $item['imagesList'] = $imagesList;

        /*
        // 评论数
        $countComment = $dynamicscommentDB->where(['dynamicsId' => $item['id']])->count();
        $item['countComment'] = $countComment;
        // 点赞数
        $countLike = $dynamicslikeDB->where(['dynamicsId' => $item['id']])->count();
        $item['countLike'] = $countLike;
        */

        // 是否已点赞
        $isLike = $dynamicslikeDB->where(['userId' => $userId, 'articleId' => $item['id']])->find();
        if($isLike){
            $isLike = 1;
        }else{
            $isLike = 2;
        }
        $item['isLike'] = $isLike;

        // 是否已关注
        $isAttention = $userattentionDB->where(['userId' => $userId, 'attentionUserId' => $item['userId']])->find();
        if($isAttention){
            $isAttention = 1;
        }else{
            $isAttention = 2;
        }
        $item['isAttention'] = $isAttention;

        $userJob = $village = '';
        if($userInfo['memberId'] && $userInfo['memberId'] !== 0){
            $memberInfo = Member::where(['id' => $userInfo['memberId']])->field('name,avatar,villageId,job')->find();
            $userJob = $memberInfo['job'];
            $village = Villages::where(['id' => $memberInfo['villageId']])->value('name');

            $item['userName'] = $memberInfo['name'];
            $item['userAvatar'] = $memberInfo['avatar'];
        }
        // 发布者职务
        $item['userJob'] = $userJob;
        // 发布者所属村子
        $item['village'] = $village;

        return $item;
    }

}